package cn.edu.sdjzu.knoverse.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.edu.sdjzu.knoverse.model.dto.system.user.*;
import cn.edu.sdjzu.knoverse.model.entity.system.User;
import cn.edu.sdjzu.knoverse.model.vo.result.PageResult;
import cn.edu.sdjzu.knoverse.model.vo.result.Result;
import cn.edu.sdjzu.knoverse.model.vo.result.ResultCodeEnum;
import cn.edu.sdjzu.knoverse.model.vo.system.user.*;
import cn.edu.sdjzu.knoverse.service.UserService;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.builder.ExcelWriterBuilder;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;


@Tag(name = "用户信息", description = "用户信息相关接口")
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @SaCheckPermission("user::getAdminUserList")
    @Operation(summary = "分页查询用户信息", description = "分页查询用户信息")
    @GetMapping("getAdminUserList/{page}/{limit}")
    public Result<PageResult<AdminUserVo>> getAdminUserList(
            @Parameter(name = "page", description = "当前页", required = true)
            @PathVariable("page") Integer page,
            @Parameter(name = "limit", description = "每页记录数", required = true)
            @PathVariable("limit") Integer limit,
            AdminUserDto dto) {
        Page<User> pageParams = new Page<>(page, limit);
        PageResult<AdminUserVo> pageResult = userService.getAdminUserList(pageParams, dto);
        return Result.success(pageResult);
    }

    @SaCheckPermission("user::getUserinfoById")
    @Operation(summary = "获取用户信息", description = "根据用户ID获取用户信息，不包含Redis中的信息")
    @GetMapping("getUserinfoById")
    public Result<UserVo> getUserinfoById(Long id) {
        UserVo vo = userService.getUserinfoById(id);
        return Result.success(vo);
    }

    @Operation(summary = "多条件查询用户", description = "多条件查询用户")
    @GetMapping("noManage/queryUser")
    public Result<List<SearchUserinfoVo>> queryUser(String keyword) {
        List<SearchUserinfoVo> voList = userService.queryUser(keyword);
        return Result.success(voList);
    }

    @SaCheckPermission("user::updateAdminUser")
    @Operation(summary = "更新用户信息", description = "更新用户信息，需要更新Redis中的内容")
    @PutMapping("updateAdminUser")
    public Result<String> updateAdminUser(@Valid @RequestBody AdminUserUpdateDto dto) {
        userService.updateAdminUser(dto);
        return Result.success(ResultCodeEnum.UPDATE_SUCCESS);
    }

    @SaCheckPermission("user::updateUserPasswordByAdmin")
    @Operation(summary = "管理员修改用户密码", description = "管理员修改管理员用户密码")
    @PutMapping("updateUserPasswordByAdmin")
    public Result<String> updateUserPasswordByAdmin(@Valid @RequestBody AdminUserUpdateWithPasswordDto dto) {
        userService.updateUserPasswordByAdmin(dto);
        return Result.success(ResultCodeEnum.UPDATE_SUCCESS);
    }

    @SaCheckPermission("user::updateUserStatusByAdmin")
    @Operation(summary = "修改用户状态", description = "管理员修改用户状态")
    @PutMapping("updateUserStatusByAdmin")
    public Result<String> updateUserStatusByAdmin(@Valid @RequestBody AdminUserUpdateUserStatusDto dto) {
        userService.updateUserStatusByAdmin(dto);
        return Result.success(ResultCodeEnum.UPDATE_SUCCESS);
    }

    @SaCheckPermission("user::uploadAvatarByAdmin")
    @Operation(summary = "修改用户头像", description = "管理员修改用户头像")
    @PutMapping("uploadAvatarByAdmin")
    public Result<String> uploadAvatarByAdmin(@Valid UserUpdateWithAvatarDto dto) {
        userService.uploadAvatarByAdmin(dto);
        return Result.success(ResultCodeEnum.UPDATE_SUCCESS);
    }

    @SaCheckPermission("user::forcedOffline")
    @Operation(summary = "强制退出", description = "强制退出")
    @PutMapping("forcedOffline")
    public Result<String> forcedOffline(@RequestBody ForcedOfflineDto dto) {
        if (dto != null && dto.getId() != null) {
            Long userId = Long.parseLong(dto.getId());
            userService.forcedOffline(userId);
            return Result.success();
        }
        return Result.error(ResultCodeEnum.REQUEST_IS_EMPTY);
    }

    @SaCheckPermission("user::addAdminUser")
    @Operation(summary = "添加用户信息", description = "添加用户信息")
    @PostMapping("addAdminUser")
    public Result<Object> addAdminUser(@Valid @RequestBody AdminUserAddDto dto) {
        userService.addAdminUser(dto);
        return Result.success(ResultCodeEnum.ADD_SUCCESS);
    }
    
    @SaCheckPermission("user::addAdminUser")
    @Operation(summary = "Excel导入用户", description = "通过Excel批量导入用户信息")
    @PostMapping("importUserExcel")
    public Result<Object> importUserExcel(@RequestParam("file") MultipartFile file, 
                                         @RequestParam("deptId") Long deptId) {
        try {
            int count = userService.importUsersByExcel(file, deptId);
            return Result.success("成功导入用户数据");
        } catch (IOException e) {
            return Result.error(ResultCodeEnum.UPLOAD_ERROR);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
    
    @SaCheckLogin
    @Operation(summary = "下载用户导入模板", description = "下载用户批量导入的Excel模板")
    @GetMapping("downloadUserImportTemplate")
    public void downloadUserImportTemplate(HttpServletResponse response) {
        try {
            // 设置响应头信息
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            // 设置文件名称
            String fileName = URLEncoder.encode("用户导入模板", StandardCharsets.UTF_8);
            // 规范化Content-disposition头部
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            
            // 使用EasyExcel写入模板信息
            ExcelWriterBuilder writerBuilder = EasyExcel.write(response.getOutputStream(), UserImportExcelDto.class);
            
            // 创建一个示例数据和注释
            List<UserImportExcelDto> demoDataList = new ArrayList<>();
            UserImportExcelDto demoData = new UserImportExcelDto();
            demoData.setUsername("zhangsan_示例(用户名不能重复)");
            demoData.setNickname("张三(昵称)");
            demoData.setEmail("zhangsan@example.com(邮箱不能重复)");
            demoData.setPhone("13800138000(选填)");
            demoData.setPassword("123456(不填则使用默认密码)");
            demoData.setSex("男(男/女，不填默认为男)");
            demoData.setSummary("个人简介(选填)");
            demoData.setStatus("启用(启用/禁用，不填默认为启用)");
            demoDataList.add(demoData);
            
            // 写入Excel，包含示例数据
            writerBuilder.sheet("用户信息")
                .doWrite(demoDataList);
        } catch (IOException e) {
            // 如果发生IO异常，记录日志
            throw new RuntimeException("下载模板失败");
        }
    }

    @SaCheckPermission("user::deleteAdminUser")
    @Operation(summary = "删除用户", description = "删除用户")
    @DeleteMapping("deleteAdminUser")
    public Result<String> deleteAdminUser(@RequestBody List<Long> ids) {
        userService.deleteAdminUser(ids);
        return Result.success(ResultCodeEnum.DELETE_SUCCESS);
    }
}